package com.example.paizhaogou;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.paizhaogou.Adapter.ItemRecycleAdapter;
import com.example.paizhaogou.Entity.Item;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

public class JdScan {
    private final static String APP_KEY = "54c00bc1aaa83fee7bcd951ab5e0ed1b";
    private final static String SECRET_KEY = "af7388ab52d512ae2f38c00d4312875a";
    private final static String API_URL = "https://aiapi.jd.com/jdai/snapshop";

    private static ArrayList<Item> items = new ArrayList<Item>();//储存respond得到的item
    private static boolean flag = false;

    public void postToJd(Bitmap bitmap, Context context,
                                AssetManager assetManager, Resources resources) {
        OkHttpClient client = new OkHttpClient();
        MediaType type = MediaType.parse("text/plain; charset=utf-8");
        String s = bitmap2String(bitmap);
        RequestBody requestBody = RequestBody.create(type, "&imgBase64=" + s + "&channel_id=test");
        final Request request = new Request.Builder()
                .url(getRequestUrl())
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("jdscan", "连接失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() == null) {
                    Log.d("jdscan", "没有得到回复!");
                    response.close();
                }
                String result = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    String itemInfoResult = jsonObject.getString("result");  //逐层解析json
                    JSONObject resultJson = new JSONObject(itemInfoResult);
                    itemInfoResult = resultJson.getString("dataValue");
                    JSONArray dataValueJsonArray = new JSONArray(itemInfoResult);
                    JSONObject dataValueJson = dataValueJsonArray.getJSONObject(0);
                    JSONArray itemArray = dataValueJson.getJSONArray("sims");

                    Gson gson = new Gson();//利用gson
                    for (int i = 0; i < itemArray.length(); i++) {
                        JSONObject item_json = itemArray.getJSONObject(i);
//                        //获取商品的图片路径
//                        String name=item_json.getString("skuName");
//                        String imageUri=item_json.getString("allImageUris");
//                        JSONArray jsonArray=new JSONArray(imageUri);
//                        imageUri=jsonArray.getString(0);
//                        String price=item_json.getString("skuPrice");
//                        String url=item_json.getString("detailUrl");
                        //创建Item类存放图片与信息
                        Item item = gson.fromJson(item_json.toString(), Item.class);
                        items.add(item);
                    }

                    JSONObject item_json = itemArray.getJSONObject(0);
                    Item item = gson.fromJson(item_json.toString(), Item.class);
                    final String[] itemName = {item.getSkuName()};

////下两行注释是利用tensorflow模型来简化商品名字的代码块
//                    SimplifyName simplifyName = new SimplifyName(itemName[0]);
//                    itemName[0] = simplifyName.simplify(assetManager, resources);
//                    while (!simplifyName.isFlag()) {
//                        continue;
//                    }
//
//                    textView.setText("检测到" + itemName[0]);
                    flag = true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


        });

    }

    public static boolean isFlag() {
        return flag;
    }

    public static ArrayList<Item> getItems() {
        return items;
    }

    private static String getRequestUrl() {//得到url
        String timestamp = "" + System.currentTimeMillis();//得到时间戳
        return API_URL + "?appkey=" + APP_KEY + "&timestamp=" + timestamp + "&sign=" + getMD5(timestamp);
    }

    public static String bitmap2String(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String getMD5(String Timestamp) {   //转义MD5
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            String origin = SECRET_KEY + Timestamp;
            byte[] bytes = digest.digest(origin.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                int c = b & 0xff; //负数转换成正数
                String result = Integer.toHexString(c); //把十进制的数转换成十六进制的书
                if (result.length() < 2) {
                    sb.append(0); //让十六进制全部都是两位数
                }
                sb.append(result);
            }
            return sb.toString(); //返回加密后的密文
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
}
